﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QueueUnlimited.API;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Transactions;
using System.Diagnostics;

namespace MultiplayerDice.Implementation.Processor
{
    public static class LastUserProcessor
    {
        public static void Process(GenericEvent genericEvent)
        {
            try
            {
                if (genericEvent.Name == typeof(BusinessEvent.NewPlayerRegisteredEvent).FullName)
                {
                    var businessEvent = genericEvent.Deserialize<BusinessEvent.NewPlayerRegisteredEvent>();

                    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
                    using (var database = new QueryDataStoreContext())
                    {
                        if (database.Query_LastUsers.Count() > 10)
                        {
                            // Only last 10: so let's delete the oldest if there are more than 10
                            database.Query_LastUsers.DeleteOnSubmit(
                                (from x in database.Query_LastUsers
                                 orderby x.InsertDateTime ascending
                                 select x).First());
                        }
                        database.Query_LastUsers.InsertOnSubmit(
                                new Query_LastUser()
                                {
                                    InsertDateTime = businessEvent.DateTimeOfRegistration,
                                    Name = businessEvent.PlayerName
                                });
                        database.SubmitChanges();
                        // Insert the new player
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
                throw;
            }
        }
    }
}
